package com.jiuyin.dianjing.ui.activity.main;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.SectionsPagerAdapter;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.app.JGApplication;
import com.jiuyin.dianjing.bottomnavigationviewex.BottomNavigationViewEx;
import com.jiuyin.dianjing.event.RefreshEvent;
import com.jiuyin.dianjing.jiguang.TagAliasOperatorHelper;
import com.jiuyin.dianjing.permission.XPermission;
import com.jiuyin.dianjing.receiver.OrderReceiver;
import com.jiuyin.dianjing.ui.activity.base.BaseActivity;
import com.jiuyin.dianjing.ui.fragment.main.FragmentFirst;
import com.jiuyin.dianjing.ui.fragment.main.FragmentFive;
import com.jiuyin.dianjing.ui.fragment.main.FragmentSecond;
import com.jiuyin.dianjing.ui.fragment.main.FragmentThird;
import com.jiuyin.dianjing.util.LogUtil;
import com.jiuyin.dianjing.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.jmessage.support.google.gson.Gson;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.callback.GetUserInfoListCallback;
import cn.jpush.im.android.api.event.ContactNotifyEvent;
import cn.jpush.im.android.api.event.GroupApprovalEvent;
import cn.jpush.im.android.api.event.GroupApprovalRefuseEvent;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;
import jiguang.database.FriendEntry;
import jiguang.database.FriendRecommendEntry;
import jiguang.database.GroupApplyEntry;
import jiguang.database.RefuseGroupEntry;
import jiguang.database.UserEntry;
import jiguang.entity.Event;
import jiguang.entity.EventType;
import jiguang.entity.FriendInvitation;
import jiguang.entity.GroupApplyInvitation;
import jiguang.pinyin.HanziToPinyin;
import jiguang.ui.fragment.conversation.ConversationListFragment;
import jiguang.util.SharePreferenceManager;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_MESSAGE;
import static com.jiuyin.dianjing.app.HelperApplication.getContext;
import static com.jiuyin.dianjing.constant.AppConstant.ACTION_NEED_LOGIN;
import static com.jiuyin.dianjing.constant.AppConstant.ACTION_ORDER_UPLOAD;
import static com.jiuyin.dianjing.jiguang.TagAliasOperatorHelper.ACTION_SET;
import static com.jiuyin.dianjing.jiguang.TagAliasOperatorHelper.sequence;

public class MainActivity extends BaseActivity {
    @BindView(R.id.vp_view_container)
    ViewPager mViewPager;

    @BindView(R.id.bottom_nav_view)
    BottomNavigationViewEx mBottomNavView;
    QBadgeView qBadgeView;
    private final List<Fragment> mListFragment = new ArrayList<>();
    private final CusReceiver mCusReceiver = new CusReceiver();
    private final OrderReceiver mOrderReceiver = new OrderReceiver();
    //消息模块初始化
    private boolean mMsgInit = false;
    private SectionsPagerAdapter mSectionsPagerAdapter;

    private final BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_first:
                    mViewPager.setCurrentItem(0);
                    return true;
                case R.id.navigation_second:
                    mViewPager.setCurrentItem(1);
                    return true;
                case R.id.navigation_third:
                    mViewPager.setCurrentItem(2);
                    return true;
                case R.id.navigation_four:
                    if (mMsgInit) {
                        mViewPager.setCurrentItem(3);
                    } else {
                        ToastUtil.showShort("消息初始化中...");
                    }
                    return true;
                case R.id.navigation_five:
                    mViewPager.setCurrentItem(4);
                    return true;
                default:
                    break;
            }
            return false;
        }
    };


    @Override
    protected int setLayoutId() {
        return R.layout.app_bar_main;
    }

    /**
     * 极光设置别名
     */
    private void jPushSetAlias() {
        TagAliasOperatorHelper.TagAliasBean tagAliasBean = new TagAliasOperatorHelper.TagAliasBean();
        tagAliasBean.action = ACTION_SET;
        sequence++;
        tagAliasBean.alias = HelperApplication.getUserId();
        LogUtil.log("userId = " + HelperApplication.getUserId());
        tagAliasBean.isAliasAction = true;
        TagAliasOperatorHelper.getInstance().handleAction(getApplicationContext(), sequence, tagAliasBean);
    }

    /**
     * 极光IM登录
     */

    private void jMessageLogin() {
        String userId = HelperApplication.getJgName();
        String pwd = HelperApplication.getJgPwd();
        if (!TextUtils.isEmpty(userId) && !TextUtils.isEmpty(pwd)) {
            JMessageClient.login(userId, pwd, new BasicCallback() {
                @Override
                public void gotResult(int i, String s) {
                    LogUtil.log("jMessageLogin gotResult i = " + i + " s = " + s);
                    if (0 == i) {
                        mMsgInit = true;
                        UserInfo myInfo = JMessageClient.getMyInfo();
                        String username = myInfo.getUserName();
                        String appKey = myInfo.getAppKey();
                        UserEntry user = UserEntry.getUser(username, appKey);
                        if (null == user) {
                            user = new UserEntry(username, appKey);
                            user.save();
                        }
                        //升级参数错误，重新登录
                    } else {
                        reLogin();
                    }
                }
            });
        } else {
            reLogin();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String message = intent.getStringExtra(KEY_MESSAGE);
        if (!TextUtils.isEmpty(message)) {
            if (message.equals("1")) {
                mViewPager.setCurrentItem(3);
            }
        }
    }

    @Override
    protected void initData() {
        JMessageClient.registerEventReceiver(this);
        EventBus.getDefault().register(this);
        jPushSetAlias();
        jMessageLogin();
        registerReceiver();
        mListFragment.add(new FragmentFirst());
        mListFragment.add(new FragmentSecond());
        mListFragment.add(new FragmentThird());
        mListFragment.add(new ConversationListFragment());
        mListFragment.add(new FragmentFive());
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), mListFragment);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                mBottomNavView.setSelectedItemId(mBottomNavView.getMenu().getItem(position).getItemId());
            }
        });
        mViewPager.setOffscreenPageLimit(mListFragment.size());
        mViewPager.setCurrentItem(0);
        mBottomNavView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        mBottomNavView.setItemIconTintList(null);
        XPermission.getNoticePermissions(this);
    }


    @Override
    protected void initView() {
        int showNum = SharePreferenceManager.getCachedNewFriendNum() + SharePreferenceManager.getUnReadMsgNum();
        addBadgeAt(3, showNum);
    }

    /**
     * 主页按返回键返回桌面，程序不退出再次点击图标直接进入程序
     * 类似支付宝效果
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
        } else {
            return false;
        }
        return true;
    }

    protected void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_NEED_LOGIN);
        intentFilter.addAction(ACTION_ORDER_UPLOAD);
        LocalBroadcastManager.getInstance(getContext()).registerReceiver(mCusReceiver, intentFilter);
        IntentFilter orderIntentFilter = new IntentFilter();
        orderIntentFilter.addAction(ACTION_ORDER_UPLOAD);
        registerReceiver(mOrderReceiver, orderIntentFilter);
    }

    protected void unRegisterReceiver() {
        LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mCusReceiver);
        unregisterReceiver(mOrderReceiver);
    }

    @Override
    protected void onDestroy() {
        unRegisterReceiver();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    /**
     * token过期，重新登录
     */
    private void reLogin() {
        quitAndLogin();
    }

    private class CusReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null) {
                return;
            }
            LogUtil.log("MainActivity onReceive action " + action);
            if (ACTION_NEED_LOGIN.equals(action)) {
                reLogin();
            }
        }
    }

    //接收到好友事件
    public void onEvent(ContactNotifyEvent event) {
        LogUtil.log("ContactNotifyEvent " + event.toString());
        final UserEntry user = JGApplication.getUserEntry();
        final String reason = event.getReason();
        final String username = event.getFromUsername();
        final String appKey = event.getfromUserAppKey();
        //对方接收了你的好友请求
        if (event.getType() == ContactNotifyEvent.Type.invite_accepted) {
            JMessageClient.getUserInfo(username, appKey, new GetUserInfoCallback() {
                @Override
                public void gotResult(int responseCode, String responseMessage, UserInfo info) {
                    if (responseCode == 0) {
                        String name = info.getNickname();
                        if (TextUtils.isEmpty(name)) {
                            name = info.getUserName();
                        }
                        FriendEntry friendEntry = FriendEntry.getFriend(user, username, appKey);
                        if (friendEntry == null) {
                            final FriendEntry newFriend = new FriendEntry(info.getUserID(), username, info.getNotename(), info.getNickname(), appKey, info.getAvatar(), name, getLetter(name), user);
                            newFriend.save();
                        }
                    }
                }
            });
            FriendRecommendEntry entry = FriendRecommendEntry.getEntry(user, username, appKey);
            entry.state = FriendInvitation.ACCEPTED.getValue();
            entry.save();

            Conversation conversation = JMessageClient.getSingleConversation(username);
            if (conversation == null) {
                conversation = Conversation.createSingleConversation(username);
                EventBus.getDefault().post(new Event.Builder()
                        .setType(EventType.createConversation)
                        .setConversation(conversation)
                        .build());
            }

            //拒绝好友请求
        } else if (event.getType() == ContactNotifyEvent.Type.invite_declined) {
            JGApplication.forAddFriend.remove(username);
            FriendRecommendEntry entry = FriendRecommendEntry.getEntry(user, username, appKey);
            entry.state = FriendInvitation.BE_REFUSED.getValue();
            entry.reason = reason;
            entry.save();
            //收到好友邀请
        } else if (event.getType() == ContactNotifyEvent.Type.invite_received) {
            //如果同一个人申请多次,则只会出现一次;当点击进验证消息界面后,同一个人再次申请则可以收到
            if (JGApplication.forAddFriend.size() > 0) {
                for (String forAdd : JGApplication.forAddFriend) {
                    if (forAdd.equals(username)) {
                        return;
                    } else {
                        JGApplication.forAddFriend.add(username);
                    }
                }
            } else {
                JGApplication.forAddFriend.add(username);
            }
            JMessageClient.getUserInfo(username, appKey, new GetUserInfoCallback() {
                @Override
                public void gotResult(int status, String desc, UserInfo userInfo) {
                    if (status == 0) {
                        String name = userInfo.getNickname();
                        if (TextUtils.isEmpty(name)) {
                            name = userInfo.getUserName();
                        }
                        FriendRecommendEntry entry = FriendRecommendEntry.getEntry(user, username, appKey);
                        if (null == entry) {
                            if (null != userInfo.getAvatar()) {
                                String path = userInfo.getAvatarFile().getPath();
                                entry = new FriendRecommendEntry(userInfo.getUserID(), username, userInfo.getNotename(), userInfo.getNickname(), appKey, path,
                                        name, reason, FriendInvitation.INVITED.getValue(), user, 0);
                            } else {
                                entry = new FriendRecommendEntry(userInfo.getUserID(), username, userInfo.getNotename(), userInfo.getNickname(), appKey, null,
                                        username, reason, FriendInvitation.INVITED.getValue(), user, 0);
                            }
                        } else {
                            entry.state = FriendInvitation.INVITED.getValue();
                            entry.reason = reason;
                        }
                        entry.save();
                        //收到好友请求数字 +1
                        int showNum = SharePreferenceManager.getCachedNewFriendNum() + 1;
                        //消息数字
                        addBadgeAt(3, showNum);
                        SharePreferenceManager.setCachedNewFriendNum(showNum);
                    }
                }
            });
        } else if (event.getType() == ContactNotifyEvent.Type.contact_deleted) {
            JGApplication.forAddFriend.remove(username);
            FriendEntry friendEntry = FriendEntry.getFriend(user, username, appKey);
            friendEntry.delete();
        }
    }

    public void onEventMainThread(Event event) {
        if (event.getType() == EventType.addFriend) {
            FriendRecommendEntry recommendEntry = FriendRecommendEntry.getEntry(event.getFriendId());
            if (null != recommendEntry) {
                FriendEntry friendEntry = FriendEntry.getFriend(recommendEntry.user,
                        recommendEntry.username, recommendEntry.appKey);
                if (null == friendEntry) {
                    friendEntry = new FriendEntry(recommendEntry.uid, recommendEntry.username, recommendEntry.noteName, recommendEntry.nickName, recommendEntry.appKey,
                            recommendEntry.avatar, recommendEntry.displayName,
                            getLetter(recommendEntry.displayName), recommendEntry.user);
                    friendEntry.save();
                }
            }
        }
    }

    //群主收到群组验证事件
    public void onEvent(GroupApprovalEvent event) {
        final UserEntry user = JGApplication.getUserEntry();
        GroupApprovalEvent.Type type = event.getType();
        long gid = event.getGid();
        event.getFromUserInfo(new GetUserInfoCallback() {
            @Override
            public void gotResult(int i, String s, UserInfo fromUserInfo) {
                if (i == 0) {
                    Gson gson = new Gson();
                    event.getApprovalUserInfoList(new GetUserInfoListCallback() {
                        @Override
                        public void gotResult(int i, String s, List<UserInfo> list) {
                            if (i == 0) {
                                if (JGApplication.forAddIntoGroup.size() > 0) {
                                    for (String addName : JGApplication.forAddIntoGroup) {
                                        if (addName.equals(list.get(0).getUserName())) {
                                            return;
                                        } else {
                                            JGApplication.forAddIntoGroup.add(list.get(0).getUserName());
                                        }
                                    }
                                }
                                GroupApplyEntry entry;
                                //邀请,from是邀请方
                                if (type.equals(GroupApprovalEvent.Type.invited_into_group)) {
                                    entry = GroupApplyEntry.getEntry(user, list.get(0).getUserName(), list.get(0).getAppKey());
                                    if (entry != null) {
                                        entry.delete();
                                    }
                                    if (fromUserInfo.getAvatar() != null) {
                                        entry = new GroupApplyEntry(fromUserInfo.getUserName(), list.get(0).getUserName(), fromUserInfo.getAppKey(),
                                                list.get(0).getAvatarFile().getPath(), fromUserInfo.getDisplayName(), list.get(0).getDisplayName(),
                                                null, GroupApplyInvitation.INVITED.getValue(), gson.toJson(event), gid + "",
                                                user, 0, 0);//邀请type=0
                                    } else {
                                        entry = new GroupApplyEntry(fromUserInfo.getUserName(), list.get(0).getUserName(), fromUserInfo.getAppKey(),
                                                null, fromUserInfo.getDisplayName(), list.get(0).getDisplayName(),
                                                null, GroupApplyInvitation.INVITED.getValue(), gson.toJson(event), gid + "",
                                                user, 0, 0);//邀请type=0
                                    }
                                } else {
                                    entry = GroupApplyEntry.getEntry(user, fromUserInfo.getUserName(), fromUserInfo.getAppKey());
                                    if (entry != null) {
                                        entry.delete();
                                    }
                                    if (fromUserInfo.getAvatar() != null) {
                                        entry = new GroupApplyEntry(list.get(0).getUserName(), list.get(0).getUserName(), list.get(0).getAppKey(),
                                                list.get(0).getAvatarFile().getPath(), list.get(0).getDisplayName(), list.get(0).getDisplayName(),
                                                event.getReason(), GroupApplyInvitation.INVITED.getValue(), gson.toJson(event), gid + "",
                                                user, 0, 1);//申请type=1
                                    } else {
                                        entry = new GroupApplyEntry(list.get(0).getUserName(), list.get(0).getUserName(), list.get(0).getAppKey(),
                                                null, fromUserInfo.getDisplayName(), list.get(0).getDisplayName(),
                                                event.getReason(), GroupApplyInvitation.INVITED.getValue(), gson.toJson(event), gid + "",
                                                user, 0, 1);//申请type=1
                                    }
                                }
                                entry.save();

                                int showNum = SharePreferenceManager.getCachedNewFriendNum() + 1;
                                //消息数字
                                addBadgeAt(3, showNum);
                                SharePreferenceManager.setCachedNewFriendNum(showNum);
                            }
                        }
                    });

                }
            }
        });
    }

    //收到被拒绝事件
    public void onEvent(GroupApprovalRefuseEvent event) {
        final UserEntry user = JGApplication.getUserEntry();
        long gid = event.getGid();
        event.getToUserInfoList(new GetUserInfoListCallback() {
            @Override
            public void gotResult(int i, String s, List<UserInfo> list) {
                if (i == 0) {
                    String userName = list.get(0).getUserName();
                    String displayName = list.get(0).getDisplayName();
                    String appKey = list.get(0).getAppKey();
                    String path = null;
                    if (list.get(0).getAvatar() != null) {
                        path = list.get(0).getAvatarFile().getPath();
                    }
                    RefuseGroupEntry groupEntry = RefuseGroupEntry.getEntry(user, userName, appKey);
                    if (groupEntry != null) {
                        groupEntry.delete();
                    }
                    groupEntry = new RefuseGroupEntry(user, userName, displayName, gid + "", appKey, path);
                    groupEntry.save();

                }
            }
        });

    }

    private String getLetter(String name) {
        String letter;
        ArrayList<HanziToPinyin.Token> tokens = HanziToPinyin.getInstance()
                .get(name);
        StringBuilder sb = new StringBuilder();
        if (tokens != null && tokens.size() > 0) {
            for (HanziToPinyin.Token token : tokens) {
                if (token.type == HanziToPinyin.Token.PINYIN) {
                    sb.append(token.target);
                } else {
                    sb.append(token.source);
                }
            }
        }
        String sortString = sb.toString().substring(0, 1).toUpperCase();
        if (sortString.matches("[A-Z]")) {
            letter = sortString.toUpperCase();
        } else {
            letter = "#";
        }
        return letter;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RefreshEvent event) {
        if (event.clazzName.equals(getClass().getSimpleName())) {
            int showNum = SharePreferenceManager.getCachedNewFriendNum() + SharePreferenceManager.getUnReadMsgNum();
            addBadgeAt(3, showNum);
        }
    }

    private Badge addBadgeAt(int position, int number) {
        HelperApplication.setBadger(number);
        if (qBadgeView == null) {
            qBadgeView = new QBadgeView(this);
        }
        return qBadgeView.setBadgeNumber(number)
                .setGravityOffset(12, 2, true)
                .bindTarget(mBottomNavView.getBottomNavigationItemView(position));
    }
}

